//
//  HMContactsViewController.m
//  HMWeChat
//
//  Created by apple on 2017/5/10.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMContactsViewController.h"
#import "HMChatViewController.h"

@interface HMContactsViewController ()<NSFetchedResultsControllerDelegate>
//查询结果控制器
@property (nonatomic, strong) NSFetchedResultsController *fetchController;
//联系人列表
@property (nonatomic, strong) NSArray <XMPPUserCoreDataStorageObject *> *contacts;

@end

@implementation HMContactsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /**
     * 选择数据库查询方式时,需要使用查询结果控制器,因为xmppframework会自动同步服务端保存的好友关系,并且保存到数据库中,为了及时展示最新的好友关系,我们可以通过监听数据库变化,相当于就可以和服务端的好友关系保持同步,监听数据库变化可以利用上下文来间接完成(CoreData进行数据库存储时一定会使用上下文进行操作)
     */
    //刷新数据(应用启动,先从本地数据库中读取缓存数据)
    [self refreshData];
}

//刷新数据
- (void)refreshData{
    
    //执行查询
        BOOL success = [self.fetchController performFetch:nil];
        
        if (success) {
            //记录数据
            self.contacts = self.fetchController.fetchedObjects;
            //刷新界面
            [self.tableView reloadData];
        }
}


#pragma mark - NSFetchedResultsControllerDelegate

//上下文改变后调用
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{

    //刷新数据
    [self refreshData];
}

#pragma mark - 响应事件

- (IBAction)clickAddFriendItem:(id)sender {
    //添加好友
    [[HMXMPPManager sharedManager].xmppRoster addUser:[XMPPJID jidWithUser:@"zhangsan" domain:@"im.itcast.cn" resource:@"HM24"] withNickname:@"张三"];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    HMChatViewController *chatVc = segue.destinationViewController;
    //获取选中的行
    NSIndexPath *path = [self.tableView indexPathForSelectedRow];
    chatVc.contactJID = self.contacts[path.row].jid;
}


#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.contacts.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"contact" forIndexPath:indexPath];
    
    // 设置数据
    UILabel *jidLabel = [cell viewWithTag:1002];
    jidLabel.text = self.contacts[indexPath.row].jid.user;
    
    //设置头像
    UIImageView *avatarImgV = [cell viewWithTag:1001];
    NSData *data = [[HMXMPPManager sharedManager].xmppAvatar photoDataForJID:self.contacts[indexPath.row].jid];
    avatarImgV.image = [UIImage imageWithData:data];
    
    return cell;
}




// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除好友
        [[HMXMPPManager sharedManager].xmppRoster removeUser:self.contacts[indexPath.row].jid];
    }
}


- (NSFetchedResultsController *)fetchController{
    
    if (_fetchController == nil) {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        //设置实体
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:[XMPPRosterCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
        [fetchRequest setEntity:entity];
        // 设置谓词  规定相互订阅的才是好友
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subscription == 'both'"];
        [fetchRequest setPredicate:predicate];
        // 设置排序 jid账号的首字母升序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"jidStr" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

        _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[XMPPRosterCoreDataStorage sharedInstance].mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        
        _fetchController.delegate = self;
    }
    return _fetchController;
}


@end
